<template>
  <plain-page>
    <el-card
      shadow="never"
      style="
        margin: 0 auto;
        min-width: 1184px;
        max-width: 1340px;
        width: fit-content;
        height: calc(100vh - 154px);"
      body-style="padding: 8px;height: calc(100% - 16px);"
      v-loading="loading"
    >
      <div class="container">
        <h1>养老服务对象信息登记表</h1>
        <div ref="formContainer" class="table">
          <el-row>
            <div class="form-item" required prop="realName" >
              <el-col :span="2">
                <label>姓名</label>
              </el-col>
              <el-col :span="5" class="content">
                <el-input ref="realName" v-model.trim="form.realName" />
              </el-col>
            </div>
            <div class="form-item" required prop="sex" >
              <el-col :span="2">
                <label>性别</label>
              </el-col>
              <el-col :span="4" class="content">
                <radio-options v-model="form.sex" :options="options.gender" />
              </el-col>
            </div>
            <div class="form-item">
              <el-col :span="3">
                <label>生日</label>
              </el-col>
              <el-col :span="4" class="content">
                <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  :default-value="moment().subtract('y', 60).month(0).toDate()"
                  style="width: 100%"
                />
              </el-col>
            </div>
            <div class="form-item">
              <el-col :span="2">
                <label>年龄</label>
              </el-col>
              <el-col :span="2" class="content">
                <el-input-number v-model="form.age" :controls="false" disabled style="width: 100%;" />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item" required prop="orgId">
              <el-col :span="2">
                <label>社区</label>
              </el-col>
              <el-col :span="5" class="content">
                <org-select v-model="form.orgId" />
              </el-col>
            </div>
            <div class="form-item" :required="form.userType == 1" prop="telephone">
              <el-col :span="2">
                <label>联系电话</label>
              </el-col>
              <el-col :span="4" class="content">
                <el-input
                  ref="telephone"
                  v-model.trim="form.telephone"
                  :suffix-icon="validateStateIcon('telephone')"
                  @blur="validateUnique('telephone')"
                />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item" required prop="userType">
              <el-col :span="2">
                <label>用户类型</label>
              </el-col>
              <el-col :span="5" class="content">
                <type-select
                  v-model="form.userType"
                  :items="DictMan.items('user.type')
                    .filter(item => [1, 2, 9].includes(+item.value))
                    .map(item => ({...item, ...{value: +item.value}}))"
                  :clearable="false"
                  :disabled="mode != 'add'"
                  style="width:100%"
                />
              </el-col>
            </div>
            <div v-show="[2, 9].includes(form.userType)" class="form-item" :required="[2, 9].includes(form.userType)" prop="deviceCode">
              <el-col :span="2">
                <label>{{{2: '会员卡号', 9: '设备编号'}[form.userType]}}</label>
              </el-col>
              <el-col :span="4" class="content">
                <el-input
                  ref="deviceCode"
                  v-model.trim="form.deviceCode"
                  :disabled="mode != 'add'"
                  :suffix-icon="validateStateIcon('deviceCode')"
                  @blur="validateUnique('deviceCode')"
                />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item" prop="visitType">
              <el-col :span="2">
                <label>调访类别</label>
              </el-col>
              <el-col :span="11" class="content">
                <checkbox-options v-model="form.visitType" :options="options.visitType" />
              </el-col>
            </div>
            <div class="form-item" prop="firstVisitDate" :required="form.visitType && form.visitType.length > 0">
              <el-col :span="3">
                <label>首次调访日期</label>
              </el-col>
              <el-col :span="4" class="content">
                <el-date-picker
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  v-model="form.firstVisitDate"
                  style="width: 100%;"
                />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item">
              <el-col :span="2">
                <label>身份证号</label>
              </el-col>
              <el-col :span="5" class="content">
                <el-input
                  ref="idcard"
                  v-model.trim="form.idcard"
                  :suffix-icon="validateStateIcon('idcard')"
                  @input="validateIdcard"
                />
              </el-col>
            </div>
            <div class="form-item">
              <el-col :span="2">
                <label>民族</label>
              </el-col>
              <el-col :span="4" class="content">
                <radio-options v-model="form.nation" :options="options.nation" />
              </el-col>
            </div>
            <div class="form-item" prop="domicileLocation">
              <el-col :span="3">
                <label>户籍所在地</label>
              </el-col>
              <el-col :span="4" class="content">
                <area-select
                  v-model="form.domicileLocation"
                  placeholder="地区"
                  style="width: 100%;"
                />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item">
              
              <el-col :span="2">
                <label>社保卡号</label>
              </el-col>
              <el-col :span="5" class="content">
                <el-input v-model.trim="form.ssn"></el-input>
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item">
              <el-col :span="2">
                <label>文化程度</label>
              </el-col>
              <el-col :span="11" class="content">
                <radio-options v-model="form.educationLevel" :options="options.educationLevel" />
              </el-col>
            </div>
            <div class="form-item">
              <el-col :span="3">
                <label>宗教信仰</label>
              </el-col>
              <el-col :span="3" class="content">
                <radio-options v-model="form.hasFaith" :options="options.haveOrNo"/>
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item">
              <el-col :span="2">
                <label>婚姻状况</label>
              </el-col>
              <el-col :span="22" class="content">
                <radio-options v-model="form.maritalStatus" :options="options.maritalStatus" />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <el-col :span="2">
              <label>居住地址</label>
            </el-col>
            <div v-if="mode == 'add'" class="form-item" prop="area">
              <el-col :span="5" class="content">
                <area-select
                  v-model="form.area"
                  placeholder="地区"
                  style="width: 100%;"
                />
              </el-col>
            </div>
            <div class="form-item">
              <el-col :span="mode == 'add' ? 6 : 11" class="content">
                <el-input v-model.trim="form.address" placeholder="详细"></el-input>
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item">
              <el-col :span="2">
                <label>紧急联系人</label>
              </el-col>
              <el-col :span="5" class="content">
                <el-input v-model.trim="form.name"></el-input>
              </el-col>
            </div>
            <div class="form-item">
              <el-col :span="2">
                <label>联系电话</label>
              </el-col>
              <el-col :span="4" class="content">
                <el-input v-model.trim="form.contactTel"></el-input>
              </el-col>
            </div>
            <div class="form-item">
              <el-col :span="3">
                <label>与服务对象的关系</label>
              </el-col>
              <el-col :span="4" class="content">
                <el-input v-model.trim="form.urgentContactPersonRelation"></el-input>
              </el-col>
            </div>
          </el-row>
          <el-row>
            <el-col :span="2">
              <label>联系人地址</label>
            </el-col>
            <div class="form-item" prop="urgentContactPersonArea">
              <el-col :span="5" class="content">
                <area-select
                  v-model="form.urgentContactPersonArea"
                  placeholder="地区"
                  style="width: 100%;"
                />
              </el-col>
            </div>
            <div class="form-item">
              <el-col :span="mode == 'add' ? 6 : 11" class="content">
                <el-input v-model.trim="form.urgentContactPersonAddress" placeholder="详细"></el-input>
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item" prop="paidMedicalExpenses">
              <el-col :span="2">
                <label>医疗费支付</label>
              </el-col>
              <el-col :span="22" class="content">
                <checkbox-options v-model="form.paidMedicalExpenses" :options="options.paidMedicalExpenses" />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <el-col :span="2" class="rowspan-3">
              <label>服务对象</label>
            </el-col>
            <el-col :span="22" class="inner rowspan-2">
              <el-row>
                <div class="form-item" prop="specialTypes">
                  <el-col :span="2" class="rowspan-2">
                    <label>特殊老人</label>
                  </el-col>
                  <el-col :span="22" class="content rowspan-2">
                    <checkbox-options v-model="form.specialTypes" :options="options.specialTypes" />
                  </el-col>
                </div>
              </el-row>
              <el-row>
                <div class="form-item">
                  <el-col :span="2">
                    <label>能力评估</label>
                  </el-col>
                  <el-col :span="22" class="content">
                    <radio-options v-model="form.ability" :options="options.ability" />
                  </el-col>
                </div>
              </el-row>
            </el-col>
          </el-row>
          <el-row v-if="form.specialTypes && form.specialTypes.includes('21')">
            <el-col :span="2">
              <label>评估对象</label>
            </el-col>
            <el-col :span="22" class="inner">
              <div class="form-item" prop="cityAllowanceEvalStatus">
                <el-col :span="2">
                  <label>评估状态</label>
                </el-col>
                <el-col :span="4" class="content">
                  <radio-options v-model="form.cityAllowanceEvalStatus" :options="options.cityAllowanceEvalStatus" />
                </el-col>
              </div>
              <div class="form-item" prop="cityAllowanceEvalScore">
                <el-col :span="2">
                  <label>评估分数</label>
                </el-col>
                <el-col :span="2" class="content">
                  <el-input-number v-model="form.cityAllowanceEvalScore" :min="0" :max="100" :controls="false" style="width: 100%;" />
                </el-col>
              </div>
              <div class="form-item" prop="cityAllowanceAmount">
                <el-col :span="3">
                  <label>拟享受市补贴</label>
                </el-col>
                <el-col :span="2" class="content">
                  <el-input-number v-model="form.cityAllowanceAmount" :controls="false" style="width: 100%;" />
                </el-col>
              </div>
              <div class="form-item" prop="cityAllowanceEvalOrgan">
                <el-col :span="2">
                  <label>评估机构</label>
                </el-col>
                <el-col :span="7" class="content">
                  <el-input v-model="form.cityAllowanceEvalOrgan" style="width: 100%;" />
                </el-col>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <div class="form-item">
              <el-col :span="2">
                <label>居住状况</label>
              </el-col>
              <el-col :span="22" class="content">
                <radio-options v-model="form.liveStatus" :options="options.liveStatus" />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <el-col :span="2" class="rowspan-6">
              <label>健康状况</label>
            </el-col>
            <el-col :span="22" class="inner rowspan-6">
              <el-row>
                <div class="form-item" prop="disease">
                  <el-col :span="2" class="rowspan-2">
                    <label>疾病</label>
                  </el-col>
                  <el-col :span="22" class="content rowspan-2">
                    <checkbox-options v-model="form.disease" :options="options.disease" />
                  </el-col>
                </div>
              </el-row>
              <el-row>
                <div class="form-item">
                  <el-col :span="2">
                    <label>重大疾病</label>
                  </el-col>
                  <el-col :span="3" class="content">
                    <radio-options v-model="form.hasMajorDisease" :options="options.haveOrNo"/>
                  </el-col>
                </div>
              </el-row>
              <el-row>
                <div class="form-item">
                  <el-col :span="2">
                    <label>重疾办理</label>
                  </el-col>
                  <el-col :span="14" class="content">
                    <radio-options v-model="form.majorDiseaseHandled" :options="options.yesno"/>
                  </el-col>
                </div>
              </el-row>
              <el-row>
                <div class="form-item">
                  <el-col :span="2">
                    <label>康复状况</label>
                  </el-col>
                  <el-col :span="22" class="content">
                    <radio-options v-model="form.recoveryStatus" :options="options.recoveryStatus" />
                  </el-col>
                </div>
              </el-row>
              <el-row>
                <div class="form-item" prop="disability">
                  <el-col :span="2">
                    <label>残障</label>
                  </el-col>
                  <el-col :span="22" class="content">
                    <checkbox-options v-model="form.disability" :options="options.disability" />
                  </el-col>
                </div>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="2" class="rowspan-2">
              <label>养老服务需求</label>
            </el-col>
            <el-col :span="22" class="inner">
              <el-row>
                <div class="form-item" prop="homeCareNeeds">
                  <el-col :span="2">
                    <label>居家养老</label>
                  </el-col>
                  <el-col :span="22" class="content">
                    <checkbox-options v-model="form.homeCareNeeds" :options="options.homeCareNeeds" />
                  </el-col>
                </div>
              </el-row>
              <el-row>
                <div class="form-item">
                  <el-col :span="2">
                    <label>机构养老</label>
                  </el-col>
                  <el-col :span="22" class="content">
                    <radio-options v-model="form.orgCareNeed" :options="options.haveNeed" />
                  </el-col>
                </div>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <div class="form-item" prop="hobbies">
              <el-col :span="2">
                <label>兴趣爱好</label>
              </el-col>
              <el-col :span="22" class="content">
                <checkbox-options v-model="form.hobbies" :options="options.hobby" />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item">
              <el-col :span="2">
                <label>特长技能</label>
              </el-col>
              <el-col :span="22" class="content">
                <radio-options v-model="form.hasSkill" :options="options.haveOrNo" />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item" prop="volunteerServiceCategories">
              <el-col :span="2">
                <label>志愿者参与</label>
              </el-col>
              <el-col :span="22" class="content">
                <checkbox-options v-model="form.volunteerServiceCategories" :options="options.volunteerServiceCategories" />
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item">
              <el-col :span="2">
                <label>对社区居家养老需求与建议</label>
              </el-col>
              <el-col :span="22" class="content rowspan-2">
                <el-input v-model.trim="form.homeCareProposal" type="textarea"></el-input>
              </el-col>
            </div>
          </el-row>
          <el-row>
            <div class="form-item">
              <el-col :span="2" class="rowspan-2">
                <label>备注及补充</label>
              </el-col>
              <el-col :span="22" class="content rowspan-2">
                <el-input v-model.trim="form.remark" type="textarea"></el-input>
              </el-col>
            </div>
          </el-row>
        </div>
      </div>
    </el-card>
    <div
      class="operations"
    >
      <el-button
        :type="mode == 'add' ? 'primary' : 'danger'"
        :icon="mode == 'add' ? 'el-icon-plus' : 'el-icon-check'"
        :loading="loading || submitting"
        style="margin-left: 10px; width: 200px;"
        @click="onSubmit"
      >{{mode == 'add' ? '登记' : '修改'}}</el-button>
      <confirm-button type="warning" plain width="200px" @ok="onResetClick">
        <p slot="content">确定重置？</p>
        重置
      </confirm-button>
    </div>
  </plain-page>
</template>
      
<script>
import RadioOptions from '@/components/RadioOptions';
import CheckboxOptions from '@/components/CheckboxOptions';
import moment from 'moment';
import idcardUtils from 'idcard';

const userTypeFieldMap = {0: 'telephone', 1: 'telephone', 2: 'deviceCode', 9: 'deviceCode'};

export default {
  pageProps: {
    title: ({params}) => params.mode == 'add' ? '增加用户' : '修改用户'
  },
  components: {
    RadioOptions,
    CheckboxOptions,
    OrgSelect: () => import('@/pages/org/OrgSelect'),
    AreaSelect: () => import('@/components/area-select/AreaSelect')
  },
  data() {
    this.moment = moment;
    
    const initialValues = {
      userType: 1,
      age: undefined,
      nation: 1,
      domicileLocation: {},
      area: {},
      urgentContactPersonArea: {},
      cityAllowanceEvalOrgan: ''
    };

    return {
      mode: this.$params.mode,
      form: {
        ...initialValues,
        ...this.$params.values
      },
      initialValues,
      validateState: {//2=验证失败,1=验证中,0=验证成功,null=待验证
        telephone: null,
        deviceCode: null,
        idcard: null
      },
      loading: this.$params.mode == 'update',
      submitting: false,
      options: {
        yesno: DictMan.items('yesno'),
        haveOrNo: DictMan.items('haveOrNo'),
        gender: DictMan.items('user.gender'),
        visitType: DictMan.items('customer.visitType'),
        nation: DictMan.items('nation'),
        educationLevel: DictMan.items('education'),
        maritalStatus: DictMan.items('user.marriage'),
        paidMedicalExpenses: DictMan.items('customer.medicalExpense'),
        specialTypes: DictMan.items('customer.specialType'),
        ability: DictMan.items('user.ability'),
        liveStatus: DictMan.items('user.liveStyle'),
        disease: DictMan.items('user.disease'),
        recoveryStatus: DictMan.items('customer.recoveryStatus'),
        disability: DictMan.items('customer.disability'),
        homeCareNeeds: DictMan.items('user.serviceNeed'),
        haveNeed: DictMan.items('customer.haveNeed'),
        hobby: DictMan.items('customer.hobby'),
        volunteerServiceCategories: DictMan.items('volunteer.service'),
        cityAllowanceEvalStatus: DictMan.items('evalOldman.evalState')
      },
    };
  },
  watch: {
    'form.birthday'(value) {
      this.form.age = value ? moment.duration(moment().diff(moment(value))).years() : undefined;
    },
    'form.specialTypes'(val) {
      // 如果选中了 留守老人，并且还未选中或不是选中 空巢或独居 时，默认选择 空巢
      if (val && val.includes('20') && !['2', '6'].includes(this.form.liveStatus)) {
        this.form.liveStatus = '6';
      } else {
        this.form.liveStatus = null;
      }
      if (val) {
        if (val.includes('21')) {
          if (this.form['cityAllowanceEvalStatus'] == null)
            this.form['cityAllowanceEvalStatus'] = '1';
        } else {
          this.form['cityAllowanceEvalOrgan'] = '';
          this.form['cityAllowanceEvalStatus'] = null;
          this.form['cityAllowanceEvalScore'] = undefined;
          this.form['cityAllowanceAmount'] = undefined;
        }
      }
    }
  },
  async mounted() {
    if (this.mode == 'update') {
      this.loading = true;
      const details = await this.$http.get('/api/user/details', {params: {isForUpdate: true, userId: this.$params.user.id}});
      this.form = {...details.basic, ...details.customer};
      this.$nextTick(() => {
        this.loading = false;
      });
    } else {
      this.prepareForAdd();
    }
  },
  methods: {
    onAgeChange(value) {
      this.form.birthday = moment().subtract(value, 'years').toDate();
    },
    async onSubmit() {
      let formData = {...this.form};
      formData.aliasName = formData.realName;
      const area2CSV = (area, separator) => area
        && (typeof area == 'string'
          ? area
          : [area.prov, area.city, area.dist].filter(Boolean).join(separator || ','));

      // 遍历所有表单项
      const formItems = this.$refs.formContainer.querySelectorAll('.form-item');
      for (let formItem of formItems) {
        // 字段名
        const prop = formItem.getAttribute('prop');
        // 表单域组件
        const fieldComponent = formItem.querySelector('.content').__vue__.$children[0];
        
        // 验证 required 规则
        if (formItem.getAttribute('required') && !formData[prop]) {
          const labelText = formItem.querySelector('label').innerText;
          this.$message.error('请填写必填项 ' + labelText);
          if (fieldComponent.focus)
            fieldComponent.focus();
          return;
        }

        if (fieldComponent.$options.name == 'CheckboxOptions') {
          let value = formData[prop];
          // 将其值从数组转换为CSV
          if (value) {
            formData[prop] = typeof value == 'string' || !value ? value : value.join(',');
          }
        }
      }
      
      formData.domicileLocation = area2CSV(formData.domicileLocation);
      formData.urgentContactPersonArea = area2CSV(formData.urgentContactPersonArea);

      if (this.mode == 'add') {
        formData.area = area2CSV(formData.area, '');
        if (formData.area)
          formData.area = formData.area.replace(/,/g, '');
        formData.address = (formData.area || '') + (formData.address || '');
      }

      let result;
      if (this.mode == 'add') {
        result = await this.submitAdd(formData);
      } else {
        result = await this.submitUpdate(formData);
      }
      if (!result.success) {
        let input = this.$refs[{2: 'telephone', 3: 'deviceCode', 4: 'deviceCode'}[result.code]];
        if (input) {
          input.focus();
        }
      }
    },
    onResetClick() {
      this.form = {...this.initialValues};
    },
    validateIdcard() {
      let value = this.form.idcard;
      let idcard;
      if (!value || value.length == 0) {
        this.validateState['idcard'] = null;
        return;
      } else if (value.length == 15) {
        let ret = idcardUtils.upgrade15To18(value);
        if (ret.code == 0) {
          idcard = ret.card;
        } else {
          this.validateState['idcard'] = 2;
          return;
        }
      } else if (value.length == 18) {
        idcard = value;
      } else {
        this.validateState['idcard'] = 2;
        return;
      }
      
      let info = idcardUtils.info(value);
      this.validateState['idcard'] = info.valid ? 0 : 2;
      if (info.valid) {
        this.validateUnique('idcard').then(() => {
          this.form.sex = {M: '0', F: '1'}[info.gender];
          let [s, y, m, d] = info.birthday.toString().match(/(\d{4})(\d{2})(\d{2})/);
          this.form.birthday = [y, m, d].join('-');
          this.form.age = info.age;
          this.form.domicileLocation = {prov: info.province.text, city: info.city.text, dist: info.area.text};
          this.$message.success('已根据身份证计算出性别、生日、年龄、户籍信息');
        });
      }
    },
    async validateUnique(field) {
      const { userType } = this.form;
      let uniqueProp = this.form[field];
      if (!uniqueProp) {
        return;
      }
      let params = {userType: userType, propName: field, uniqueProp};
      if (this.mode == 'update') {
        params.userId = this.form.id;
      }
      this.validateState[field] = 1;
      const ret = await this.$http.get('/api/user/validate', {params});
      const isOk = ret.code == 0;
      this.validateState[field] = isOk ? 0 : 2;
      if (isOk) {
        // 开始自动跳到了主要字段，为方便用户，现在验证完主要字段之后，自动跳到姓名字段
        if (!this.form.realName) {
          this.$refs.realName.focus();
        }
        return true;
      }

      let user = ret.data;  // 已注册用户id

      if (user && !user.belongOrgId && app.admin.belongOrgId && this.mode == 'add') {
        this.$confirm(`查询到已注册用户【${user.realName || user.aliasName}】，但不属于当前登录账号所属组织，是否关联到当前登录账号所属组织？`, '提示', {
          confirmButtonText: '关联',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          type: 'info'
        }).then(async () => {
          const ret = await this.$http.put('/api/user/belongOrg',
            {userType, uniqueProp, belongOrgId: app.admin.belongOrgId});
          if (ret.success) {
            this.$params.onSuccess();
            this.$confirm('关联该用户成功，你可以继续操作', '温馨提示', {
              confirmButtonText: '打开用户详情',
              cancelButtonText: '打开用户修改',
              closeOnClickModal: false,
              distinguishCancelAndClose: true,
              type: 'success'
            }).then(() => {
              this.pushPage({
                path: '/user/details',
                params: { user },
                key: user.id
              });
            }).catch((action) => {
              if (action === 'cancel') {
                this.pushPage({
                  path: '/user/register',
                  key: user.id,
                  params: {
                    mode: 'update',
                    user,
                    onSuccess: () => {
                      this.$params.onSuccess();
                    }
                  }
                });
              }
            });
          }
        });
      } else {
        this.$message.error(ret.message);
      }
      return false;
    },
    validateStateIcon(field) {
      return {null: '', 0: 'el-icon-check', 1: 'el-icon-loading', 2: ''}[this.validateState[field]]; 
    },
    async submitAdd(formData) {
      if (formData.userType == 1) {
        this.form.password = '123456';
      } else {
        this.form.password = '';
      }

      this.submitting = true;
      const ret = await this.$http.post('/api/user/registUser', formData);
      this.submitting = false;
      if (ret.success) {
        this.$message.success('增加用户成功');
        this.$params.onSuccess();
        this.$pageEventBus.emit(this, 'user-add', this.form);
        this.form = {...this.initialValues};
        for (let field in this.validateState) {
          this.validateState[field] = null;
        }
        this.prepareForAdd();
      } else {
        this.$message.error(ret.message);
      }
      return ret;
    },
    async submitUpdate(formData) {
      this.submitting = true;
      formData.userId = this.form.id;
      formData.appUserId = formData.userId;
      const ret = await this.$http.post('/api/user/updateUser', formData);
      this.submitting = false;
      if (ret.success) {
        this.$message.success('修改用户成功');
        this.$pageEventBus.emit(this, 'user-update', this.form.id);
        this.$params.onSuccess();
      } else {
        this.$message.error(ret.message);
      }
      return ret;
    },
    prepareForAdd() {
      let { userType } = this.form;
      if (userType) {
        if (userType != 1) {
          this.$refs[userTypeFieldMap[this.form.userType]].focus();
        } else {
          this.$refs.idcard.focus();
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$col-min-height: 32px;

.container {
  margin: 0 auto;
  height: 100%;
  border-radius: 4px;
  background-color: #f0f2f5;

  h1 {
    margin: 0px;
    padding-top: 8px;
    margin-bottom: 8px;
    text-align: center;
    font-size: 18px;
  }

  .table {
    padding: 0px 8px 8px;
    height: calc(100% - 50px);
    overflow-x: hidden;
    overflow-y: auto;

    .el-row {
      margin-top: 16px;

      .el-col {
        line-height: $col-min-height;
        min-height: $col-min-height;
        
        .el-checkbox-group {
          max-height: $col-min-height;
        }

        &.rowspan-2 {
          height: $col-min-height * 2;

          > label {
            line-height: $col-min-height * 2;
          }
        }

        &.rowspan-3 {
          height: $col-min-height * 3;

          > label {
            line-height: $col-min-height * 3;
          }
        }

        &.rowspan-4 {
          height: $col-min-height * 4;

          > label {
            line-height: $col-min-height * 4;
          }
        }

        &.rowspan-6 {
          height: $col-min-height * 6;

          > label {
            line-height: $col-min-height * 6;
          }
        }

        &.inner {
          padding-left: 0px;

          .el-row {
            margin-top: 0px;
          }
        }
      }
    }
  }
}

.el-col > label {
  display: block;
  margin-right: 8px;
  padding: 0px 4px;
  height: 100%;
  text-align: center;
  font-size: 14px;
  color: #606266;
  background-color: #F4F8FE;
  border-radius: 4px;
}

.form-item {
  display: contents;

  &[required] {
    .el-col > label:before {
      margin-right: 4px;
      content: '*';
      color: #F56C6C;
    }
  }

  .el-col.content {
    padding-right: 16px;
  }
}
</style>

<style scoped>
>>> .el-textarea > textarea {
  height: 65px;
  resize: none;
}

>>> .rowspan-2 > .el-checkbox-group,
>>> .rowspan-2 > .el-radio-group {
  padding: 8px 0px;
  line-height: initial;
}

>>> .rowspan-2 > .el-checkbox-group > .el-checkbox,
>>> .rowspan-2 > .el-radio-group > .el-radio
 {
  margin-right: 0px;
  padding: 4px;
}

.operations {
  margin-top: 8px;
  margin-bottom: 8px;
  text-align: center;
}
</style>